package com.ja.openchat.viewmodels;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.google.gson.JsonObject;
import com.ja.openchat.ui.me.MyAlbumFragment;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.circle.BlogUserDateInfo;
import com.zy.openchat.core.model.circle.BlogUserInfo;
import com.zy.openchat.core.model.user.UserInfo;

import java.util.HashMap;
import java.util.Map;

import me.goldze.mvvmhabit.base.MultiItemViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;

public class MyFollowItemViewModel extends MultiItemViewModel<MyFollowViewModel> {
    public ObservableField<BlogUserDateInfo> entity = new ObservableField<>();
    public ObservableField<String> name = new ObservableField<>();
    public ObservableField<String> btnText = new ObservableField<>();
    public ObservableField<Integer> btnVisibly = new ObservableField<>(View.VISIBLE);
    public ObservableField<Boolean> followed = new ObservableField<>(false);

    public ObservableField<UserInfo> userAvatar = new ObservableField<>();
    boolean mShowHuiGuan;

    public MyFollowItemViewModel(@NonNull MyFollowViewModel viewModel, BlogUserDateInfo entity) {
        super(viewModel);
        this.entity.set(entity);
        mShowHuiGuan = viewModel.mType == 1 && UserInfo.getUserInfo().id == viewModel.userId;
        update(entity);


    }

    private void update(BlogUserDateInfo entity) {
        UserInfo userInfo = UserInfo.getUserInfo(entity.user_id);
        if (userInfo != null) {
            if (userInfo.profile_photo != null && !userInfo.profile_photo.isSmallPhotoDownloaded()) {
                entity.isAvaterDownloaded = false;
            } else {
                entity.isAvaterDownloaded = true;
            }
            name.set(userInfo.displayName());
            userAvatar.set(userInfo);
            userAvatar.notifyChange();
        } else {
            name.set("");
            entity.isAvaterDownloaded = false;
            TelegramManager.getTelegramManager().getUserSimpleInfo(entity.user_id);
        }

        if (entity.user_id == UserInfo.getUserInfo().id) {
            btnVisibly.set(View.GONE);
        } else {
            BlogUserInfo blogUserInfo = requestBlogUserInfo(entity.user_id);
            if (blogUserInfo != null) {
                btnVisibly.set(View.VISIBLE);
                followed.set(blogUserInfo.followed);
                if (blogUserInfo.followed) {
                    btnText.set("已关注");
                } else {
                    btnText.set(!mShowHuiGuan ? "关注" : "回关");
                }
            } else {
                btnVisibly.set(View.GONE);
            }
        }
    }

    public void cleanUserCache() {
        blogUserInfoHashMap.clear();
    }

    private HashMap<Long, BlogUserInfo> blogUserInfoHashMap = new HashMap<>();

    public BlogUserInfo requestBlogUserInfo(long userId) {
        if (blogUserInfoHashMap.containsKey(userId)) {
            return blogUserInfoHashMap.get(userId);
        } else {
            TelegramManager.getTelegramManager().getBlogUser(viewModel.getApplication(), userId, new TgResultBlock<BlogUserInfo>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, BlogUserInfo obj) {
                    updateBlogUserInfo(obj);
                }

                @Override
                public void onTimeout(Map<String, Object> request) {

                }
            });
            return null;
        }
    }

    public void updateBlogUserInfo(BlogUserInfo userInfo) {
        if (userInfo == null) {
            return;
        }
        blogUserInfoHashMap.put(userInfo.user_id, userInfo);
        if (userInfo.user_id == entity.get().user_id) {
            update(entity.get());
        }
    }

    /**
     * 获取position的方式有很多种,indexOf是其中一种，常见的还有在Adapter中、ItemBinding.of回调里
     *
     * @return
     */
    public int getPosition() {
        return viewModel.getItemPosition(this);
    }

    //条目的点击事件
    public BindingCommand itemClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            Bundle bundle = new Bundle();
            bundle.putLong("userId", entity.get().user_id);
            viewModel.startContainerActivity(MyAlbumFragment.class.getCanonicalName(), bundle);
        }
    });
    public BindingCommand itemGuanZhuClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            BlogUserInfo blogUserInfo = requestBlogUserInfo(entity.get().user_id);
            if (blogUserInfo != null) {
                boolean followed = !blogUserInfo.followed;
                if (viewModel.activity == null)
                    return;
                new XPopup.Builder(viewModel.activity).autoDismiss(true).asConfirm("提示", followed ? "确定关注此人吗？" : "确定取消关注用户?", "取消", "确定", new OnConfirmListener() {
                    @Override
                    public void onConfirm() {
                        actionFollow(entity.get(), followed);
                    }
                }, new OnCancelListener() {
                    @Override
                    public void onCancel() {

                    }
                }, false).show();
            }
        }
    });

    private void actionFollow(BlogUserDateInfo blogInfo, boolean followed) {
        viewModel.showProgress();
        TelegramManager.getTelegramManager().followBlog(viewModel.getApplication(), blogInfo.user_id, followed, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                viewModel.hideProgress();
                if (obj != null) {
                    if (obj.ok) {
                        cleanUserCache();
                        viewModel.requestData(1);
                    } else {
                        viewModel.showErrorTip(obj.errString);
                    }
                } else {
                    viewModel.showErrorTip("关注失败，请稍后重试");
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                viewModel.hideProgress();
                viewModel.showErrorTip("关注失败，请稍后重试");
            }
        });
    }

    //条目的长按事件
    public BindingCommand itemLongClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
        }
    });
}
